import {
	Platform,
	Storage_Key
} from '@/static/config.js';
import * as Storage from '@/common/storage.js'
import {
	GenerateToken
} from '@/common/util.js'

const userinfo = Storage.get(Storage_Key.user_info, true);

const request = (options = {}) => {
	return new Promise((resolve, reject) => {
		const token = uni.getStorageSync('token'); // 假设使用token进行身份验证
		const defaultOptions = {
			method: 'GET',
			url: Platform.api_requestUrl,
			header: {
				'Authorization': `Bearer ${token}`,
				'Content-Type': 'application/json',
				'openid': userinfo.openId||userinfo.openid||'',
				'system': 'app',
			},
			// dataType: 'json',
		};
		const {
			url,
			method,
			data,
			header
		} = {
			...defaultOptions,
			...options
		};
		
		uni.request({
			url,
			method,
			data,
			header,
			success: (res) => {
				// 根据后端返回的状态码进行逻辑判断
				const {
					statusCode,
					data
				} = res;
				
				if (statusCode >= 200 && statusCode < 300) {
					// 检查业务状态码
					if (data.code === 401||data.code === 403) {
						// 登录过期，清除token
						uni.removeStorageSync('token');
						uni.removeStorageSync('userinfo');
						// 提示用户重新登录
						uni.showModal({
							title: '提示',
							content: '登录已过期，请重新登录',
							showCancel: false,
							success: () => {
								// 跳转到登录页面
								uni.switchTab({
									url: '/pages/user/user'
								});
							}
						});
						reject(data);
					} else if(data.code === 500){
						reject(res);
					} else {
						resolve(data);
					}
				} else {
					// 可以根据不同的错误状态码进行不同的处理
					reject(res);
				}
			},
			fail: (err) => {
				reject(err);
			}
		});
	});
};

export default request;